<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\common\Frontend;
use app\api\model\UserCareProduct;
use app\api\model\UserHistory;
use app\api\model\UserNotLikeProduct;
use app\common\model\Navigation;
use app\common\model\Product as ModelProduct;
use app\common\model\PublicStatus;
use general\Tree;
use think\helper\Str;

class Product extends Frontend
{
    protected array $noNeedLogin = ['list', 'productDetail', 'productRecommend', 'classProduct'];

    protected $model;
    protected $tree;
    public function initialize(): void
    {
        parent::initialize();
        $res = Navigation::where(['status' => PublicStatus::PUBLIC_STATUS_ONE])->select()->toArray();
        $this->model = new ModelProduct;
        $this->tree = Tree::instance()->init($res);
    }


    //列表
    public function list(): void
    {
        $limit = $this->request->request('limit', 100);
        $res = Navigation::field('id,title,alias_title,alias_title_en')->where(['type'=>'home'])->with(['project' => function ($query) use ($limit) {
            $query->order('weigh desc')->limit(10)->select()->each(function ($item, $key) {
                if ($this->auth->isLogin()) {
                    //是否收藏
                    $is_collect = $item->careProduct()->where('user_id', $this->auth->id)->find();
                    $not_like = $item->notLikeProduct()->where('user_id', $this->auth->id)->find();
                    $item['is_collect'] = is_null($is_collect) ? false : true;
                    $item['not_like'] = is_null($not_like) ? false : true;
                    $item['not_like_show'] = is_null($not_like) ? false : true;
                }
                $item['image_url']  = full_url($item['url']);
                return $item;
            });
        }])->where(['pid' => PublicStatus::PUBLIC_STATUS_ZERO, 'status' => PublicStatus::PUBLIC_STATUS_ONE])->order('weigh desc')->select()->filter(function(Navigation $nav){
            if(count($nav['project']) > 0){
                return true;
            }
        })->toArray();


        // $res = $this->model->where('status', 1)
        //     ->order('weigh desc')
        //     ->paginate($limit)->each(function ($item, $key) {
        //         if ($this->auth->isLogin()) {
        //             //是否收藏
        //             $is_collect = $item->careProduct()->where('user_id', $this->auth->id)->find();
        //             $not_like = $item->notLikeProduct()->where('user_id', $this->auth->id)->find();
        //             $item['is_collect'] = is_null($is_collect) ? false : true;
        //             $item['not_like'] = is_null($not_like) ? false : true;
        //             $item['not_like_show'] = is_null($not_like) ? false : true;
        //         }
        //         $item['image_url']  = full_url($item['url']);
        //         return $item;
        //     });

        $this->success('', [
            'list'  => array_values($res),
            'total' => 0,
        ]);
    }



    //收藏and取消收藏
    public function careProduct(): void
    {
        $id  = $this->request->param('id');
        $row = ModelProduct::find($id);
        if (!$row) {
            $this->error('未找到相关数据');
        }
        if ($this->auth->isLogin()) {
            //关注店铺
            UserCareProduct::careProductModel($id, $this->auth->id);
        }
        $this->success();
    }


    //喜不喜欢
    public function notLickProduct(): void
    {
        $id  = $this->request->param('id');
        $row = ModelProduct::find($id);
        if (!$row) {
            $this->error('未找到相关数据');
        }
        if ($this->auth->isLogin()) {
            //关注店铺
            UserNotLikeProduct::notLikeProductModel($id, $this->auth->id);
        }
        $this->success();
    }







    //产品详情
    public function productDetail(): void
    {
        $id  = $this->request->param('id');


        $row = ModelProduct::with(['careProduct', 'productCombo' => ['combo']])->find($id);

        if (!$row) {
            $this->error(('Record not found'));
        }
        if (!empty($row['banner_path'])) {
            // $key = getMimeInfo($str);
            // $mimeType = getFileInfo($key);
            $banner_path_arr = (json_decode($row['banner_path'], true));
            $new_banner_arr = [];
            foreach ($banner_path_arr as $key => $value) {
                $qiniu_key = getMimeInfo($value);
                $mimeType = getFileInfo($qiniu_key);
                $new_banner_arr[$key]['is_video'] = Str::contains($mimeType, 'video') ? true : false;
                $new_banner_arr[$key]['path'] = $value;
            }
            $row['banner_path'] = $new_banner_arr;
            $row['banner_count'] = count($row['banner_path']);
        }
        $row['url'] = full_url($row['url']);
        if ($this->auth->isLogin()) {
            //添加浏览记录
            UserHistory::insertHistory($id, PublicStatus::PUBLIC_STATUS_ZERO, $this->auth->id);
            //是否收藏
            $is_collect = $row->careProduct()->where('user_id', $this->auth->id)->find();
            $row['is_collect'] = is_null($is_collect) ? false : true;
            $row['yearDate'] = date('Y-m-d', strtotime($row['create_time']));
        }
        // if(isJson($row['project_config'])){
        //     $row['project_config'] =  json_decode($row['project_config'], true);
        // }

        if (count($row['productCombo']) > PublicStatus::PUBLIC_STATUS_ZERO) {
            foreach ($row['productCombo'] as $key => $v) {
                if (isJson($v['combo']['content'])) {
                    $row['productCombo'][$key]['combo']['content'] = json_decode($v['combo']['content'], true);
                }
            }
        }
        $this->success('', [
            'list'   => $row,
            'remark' => '',
        ]);
    }



    //产品详情推荐
    public function productRecommend(): void
    {
        $type_id = $this->request->param('type_id');
        $childIds = $this->tree->getChildrenIds($type_id, true);
        $where[] = ['status', '=', PublicStatus::PUBLIC_STATUS_ONE];
        $where[] = ['nav_id', 'in', $childIds];
        $limit = $this->request->param('limit', 10);
        $res = $this->model->with(['navOne'])->where($where)
            ->order('weigh desc')
            ->paginate($limit)->each(function ($item, $key) {
                if ($this->auth->isLogin()) {
                    //是否收藏
                    $is_collect = $item->careProduct()->where('user_id', $this->auth->id)->find();
                    $not_like = $item->notLikeProduct()->where('user_id', $this->auth->id)->find();
                    $item['is_collect'] = is_null($is_collect) ? false : true;
                    $item['not_like'] = is_null($not_like) ? false : true;
                    $item['not_like_show'] = is_null($not_like) ? false : true;
                }
                $item['image_url']  = full_url($item['url']);
                return $item;
            });

        $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }

    //分类产品
    public function classProduct(): void
    {
        $type = $this->request->param('type', 'all');
        $where = [];
        if ($this->request->has('type') && !empty($this->request->param('type')) && $type == 'big') {
            $id = $this->request->param('pid');
            $childIds = $this->tree->getChildrenIds($id, true);
            $where[] = ['nav_id', 'in', $childIds];
        }
        if ($this->request->has('type') && !empty($this->request->param('type')) && $type == 'all') {
            $pid = $this->request->param('pid');
            $childIds = $this->tree->getChildrenIds($pid, true);
            $where[] = ['nav_id', 'in', $childIds];
        }
        if ($this->request->has('type') && !empty($this->request->param('type')) && $type == 'small') {
            $id = $this->request->param('id');
            $where[] = ['nav_id', '=', $id];
        }
        if ($this->request->has('search') && !empty($this->request->param('search'))) {
            $where[] = ['search_key', 'like', '%' . $this->request->param('search') . '%'];
        }
        $where[] = ['status', '=', PublicStatus::PUBLIC_STATUS_ONE];
        $limit = $this->request->param('limit', 10);
        $res = $this->model->where($where)
            ->order('create_time desc')
            ->paginate($limit)->each(function ($item, $key) {
                if ($this->auth->isLogin()) {
                    //是否收藏
                    $is_collect = $item->careProduct()->where('user_id', $this->auth->id)->find();
                    $not_like = $item->notLikeProduct()->where('user_id', $this->auth->id)->find();
                    $item['is_collect'] = is_null($is_collect) ? false : true;
                    $item['not_like'] = is_null($not_like) ? false : true;
                    $item['not_like_show'] = is_null($not_like) ? false : true;
                }
                $item['image_url']  = full_url($item['url']);
                return $item;
            });

        $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }



    //检查用户是否下载
    public function checkUserDownload(): void
    {
        $product_id = $this->request->param('product_id');
        $combo_id = $this->request->param('combo_id', 0);
        $res = UserHistory::where(['user_id' => $this->auth->id, 'product_id' => $product_id, 'combo_id' => $combo_id, 'type' => PublicStatus::PAY_TYPE_TWO])->findOrEmpty();

        if (!$res->isEmpty()) {
            //不为空的话
            //1.判断是否超过3天
            $day = fileModTime($res->create_time);
            if ($day) {
                //超过3天 重新收费
                $is_download = PublicStatus::USER_DOWNLOAD_STATUS_ONE;
            } else {
                $is_download = PublicStatus::USER_DOWNLOAD_STATUS_TWO;
            }
        } else {
            $is_download = PublicStatus::USER_DOWNLOAD_STATUS_THREE;
        }
        $this->success('ok', ['is_download' => $is_download]);
    }
}
